﻿using d1Common.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using d1Project.Modules.Common.do4A.Models;
using d1Common;
using d1Project.Modules.Common.do4A.Domain;
using System.Reflection;
using System.Data.Entity;
using System.Threading.Tasks;
using d1Common.WebController;
using d1Project.Tools;

namespace d1Project.Modules.Common.do4A.Services
{
    public class do4AServiceLocal : do4AServiceBase, IDo4AService
    {
        public IToken GetToken1(string _tokenValue)
        {
            if (!doServices.Instance.DoCache.ContainsKey(do4AModule.CacheGroupToken1, _tokenValue)) return null;
            Token _token = doServices.Instance.DoCache.GetData<Token>(do4AModule.CacheGroupToken1, _tokenValue);
            //最后10分钟内，延长过期时间
            if (DateTime.Now.AddMinutes(10) >= _token.ExpiredTime)
            {
                doServices.Instance.DoCache.SetData(do4AModule.CacheGroupToken1, _token.Id, _token, AuthenticationMgr.Instance.Token1_tokenDuration * 60);
            }
            return _token;
        }

        public IToken GetToken2(string _tokenValue)
        {
            if (!doServices.Instance.DoCache.ContainsKey(do4AModule.CacheGroupToken2, _tokenValue)) return null;
            Token _token = doServices.Instance.DoCache.GetData<Token>(do4AModule.CacheGroupToken2, _tokenValue);
            //最后10分钟内，延长过期时间
            if (DateTime.Now.AddMinutes(10) >= _token.ExpiredTime)
            {
                doServices.Instance.DoCache.SetData(do4AModule.CacheGroupToken2, _token.Id, _token, AuthenticationMgr.Instance.Token2_tokenDuration * 60);
            }
            return _token;
        }

        public IToken GetToken3(string _tokenValue)
        {
            if (!doServices.Instance.DoCache.ContainsKey(do4AModule.CacheGroupToken3, _tokenValue)) return null;
            Token _token = doServices.Instance.DoCache.GetData<Token>(do4AModule.CacheGroupToken3, _tokenValue);
            //最后10分钟内，延长过期时间
            if (DateTime.Now.AddMinutes(10) >= _token.ExpiredTime)
            {
                doServices.Instance.DoCache.SetData(do4AModule.CacheGroupToken3, _token.Id, _token, AuthenticationMgr.Instance.Token3_tokenDuration * 60);
            }
            return _token;
        }

        public IToken GetToken4(string _tokenValue)
        {
            if (!doServices.Instance.DoCache.ContainsKey(do4AModule.CacheGroupToken4, _tokenValue)) return null;
            Token _token = doServices.Instance.DoCache.GetData<Token>(do4AModule.CacheGroupToken4, _tokenValue);
            //最后10分钟内，延长过期时间
            if (DateTime.Now.AddMinutes(10) >= _token.ExpiredTime)
            {
                doServices.Instance.DoCache.SetData(do4AModule.CacheGroupToken4, _token.Id, _token, AuthenticationMgr.Instance.Token3_tokenDuration * 60);
            }
            return _token;
        }

        protected override IDictionary<string, IRolePermission> GetRolePermissionsData(string _roleID)
        {
            return PermissionMgr.Instance.GetRolePermissionsLocal(_roleID);
        }

        public void WriteAuditLog(string _TypeId, string _TypeName, string _userId, string _userName, string _desc)
        {
            do4ADbContext db = new do4ADbContext();
            try
            {
                AuditLogMgr.Instance.WriteAuditLog(_TypeId, _TypeName, _userId, _userName, _desc);
            }
            finally
            {
                db.Dispose();
            }
        }

        public IDoPermissionOpt getDoPermissionOpt(string _permissionId, int _optId)
        {
            return PermissionMgr.Instance.getDoPermissionOpt(_permissionId, _optId);
        }


        //获取user1信息
        public IDictionary<string, string> GetUser1Detail(string user1Id)
        {
            do4ADbContext db = new do4ADbContext();
            Dictionary<string, string> userDetail = null;
            try
            {
                var entity = db.User1s.Find(user1Id);
                if (entity != null)
                {
                    userDetail = new Dictionary<string, string>();
                    foreach (PropertyInfo pi in entity.GetType().GetProperties())
                    {
                        object obj = pi.GetValue(entity, null);
                        if (obj != null) userDetail[pi.Name] = obj.ToString();
                    }
                }
                return userDetail;
            }
            finally
            {
                db.Dispose();
            }
        }

        public async Task<IDictionary<string, string>> GetUser1DetailAsync(string user1Id)
        {
            do4ADbContext db = new do4ADbContext();
            Dictionary<string, string> userDetail = null;
            try
            {
                var entity = await db.User1s.FindAsync(user1Id);
                if (entity != null)
                {
                    userDetail = new Dictionary<string, string>();
                    foreach (PropertyInfo pi in entity.GetType().GetProperties())
                    {
                        object obj = pi.GetValue(entity, null);
                        if (obj != null) userDetail[pi.Name] = obj.ToString();
                    }
                }
                return userDetail;
            }
            finally
            {
                db.Dispose();
            }
        }


        //获取user2信息
        public IDictionary<string, string> GetUser2Detail(string user2Id)
        {
            do4ADbContext db = new do4ADbContext();
            Dictionary<string, string> userDetail = null;
            try
            {
                var entity = db.User2s.Find(user2Id);
                if (entity != null)
                {
                    userDetail = new Dictionary<string, string>();
                    foreach (PropertyInfo pi in entity.GetType().GetProperties())
                    {
                        object obj = pi.GetValue(entity, null);
                        if (obj != null) userDetail[pi.Name] = obj.ToString();
                    }
                }
                return userDetail;
            }
            finally
            {
                db.Dispose();
            }
        }

        public async Task<IDictionary<string, string>> GetUser2DetailAsync(string user2Id)
        {
            do4ADbContext db = new do4ADbContext();
            Dictionary<string, string> userDetail = null;
            try
            {
                var entity = await db.User2s.FindAsync(user2Id);
                if (entity != null)
                {
                    userDetail = new Dictionary<string, string>();
                    foreach (PropertyInfo pi in entity.GetType().GetProperties())
                    {
                        object obj = pi.GetValue(entity, null);
                        if (obj != null) userDetail[pi.Name] = obj.ToString();
                    }
                }
                return userDetail;
            }
            finally
            {
                db.Dispose();
            }
        }

        public async Task<IDictionary<string, string>> PostUser2Async(string id, string code, string mobilePhone, string email, string name, string passWord)
        {
            do4ADbContext db = new do4ADbContext();
            try
            {
                if (!string.IsNullOrEmpty(id))
                {
                    var old = await db.User2s.Where(x => x.Id == id).FirstOrDefaultAsync();
                    if (old != null) throw new UserException("Id不能重复:" + id + "已存在");
                }
                if (!string.IsNullOrEmpty(code))
                {
                    var old = await db.User2s.Where(t => t.Code == code).FirstOrDefaultAsync();
                    if (old != null) throw new UserException("编码不能重复:" + code + "已存在");
                }
                if (!string.IsNullOrEmpty(mobilePhone))
                {
                    var old = await db.User2s.Where(x => x.MobilePhone == mobilePhone).FirstOrDefaultAsync();
                    if (old != null) throw new UserException("电话不能重复:" + mobilePhone + "已存在");
                }
                if (!string.IsNullOrEmpty(email))
                {
                    var old = await db.User2s.Where(x => x.Email == email).FirstOrDefaultAsync();
                    if (old != null) throw new UserException("邮箱不能重复:" + email + "已存在");
                }

                User2 entity = new User2();
                entity.Id = doServices.Instance.DoCore.getGUID();
                if (!string.IsNullOrEmpty(id)) entity.Id = id;
                entity.Name = name;
                entity.MobilePhone = mobilePhone;
                entity.Email = email;
                entity.IsAvailable = "1";
                entity.CreateTime = DateTime.Now;
                entity.UpdateTime = DateTime.Now;
                db.User2s.Add(entity);

                User2Pwd user2pwd = new User2Pwd();
                user2pwd.Id = entity.Id;
                user2pwd.Password = TextHelper.GetMd5("123456");
                if (!string.IsNullOrEmpty(passWord)) user2pwd.Password = passWord;

                db.User2Pwds.Add(user2pwd);

                await db.SaveChangesAsync();

                Dictionary<string, string> user2 = null;
                user2 = new Dictionary<string, string>();
                foreach (PropertyInfo pi in entity.GetType().GetProperties())
                {
                    object obj = pi.GetValue(entity, null);
                    if (obj != null) user2[pi.Name] = obj.ToString();
                }
                return user2;
            }
            finally
            {
                db.Dispose();
            }
        }


        //获取user3信息
        public IDictionary<string, string> GetUser3Detail(string user3Id)
        {
            do4ADbContext db = new do4ADbContext();
            Dictionary<string, string> userDetail = null;
            try
            {
                var entity = db.User3s.Find(user3Id);
                if (entity != null)
                {
                    userDetail = new Dictionary<string, string>();
                    foreach (PropertyInfo pi in entity.GetType().GetProperties())
                    {
                        object obj = pi.GetValue(entity, null);
                        if (obj != null) userDetail[pi.Name] = obj.ToString();
                    }
                }
                return userDetail;
            }
            finally
            {
                db.Dispose();
            }
        }

        public async Task<IDictionary<string, string>> GetUser3DetailAsync(string user3Id)
        {
            do4ADbContext db = new do4ADbContext();
            Dictionary<string, string> userDetail = null;
            try
            {
                var entity = await db.User3s.FindAsync(user3Id);
                if (entity != null)
                {
                    userDetail = new Dictionary<string, string>();
                    foreach (PropertyInfo pi in entity.GetType().GetProperties())
                    {
                        object obj = pi.GetValue(entity, null);
                        if (obj != null) userDetail[pi.Name] = obj.ToString();
                    }
                }
                return userDetail;
            }
            finally
            {
                db.Dispose();
            }
        }

        public async Task<IDictionary<string, string>> PostUser3Async(string id, string code, string mobilePhone, string email, string name, string passWord)
        {
            do4ADbContext db = new do4ADbContext();
            try
            {
                if (!string.IsNullOrEmpty(id))
                {
                    var old = await db.User3s.Where(t => t.Id == id).FirstOrDefaultAsync();
                    if (old != null) throw new UserException("Id不能重复:" + id + "已存在");
                }
                if (!string.IsNullOrEmpty(code))
                {
                    var old = await db.User3s.Where(t => t.Code == code).FirstOrDefaultAsync();
                    if (old != null) throw new UserException("编码不能重复:" + code + "已存在");
                }
                if (!string.IsNullOrEmpty(mobilePhone))
                {
                    var old = await db.User3s.Where(t => t.MobilePhone == mobilePhone).FirstOrDefaultAsync();
                    if (old != null) throw new UserException("电话不能重复:" + mobilePhone + "已存在");
                }
                if (!string.IsNullOrEmpty(email))
                {
                    var old = await db.User3s.Where(t => t.Email == email).FirstOrDefaultAsync();
                    if (old != null) throw new UserException("邮箱不能重复:" + email + "已存在");
                }

                User3 entity = new User3();
                entity.Id = doServices.Instance.DoCore.getGUID();
                if (!string.IsNullOrEmpty(id)) entity.Id = id;
                entity.Name = name;
                entity.MobilePhone = mobilePhone;
                entity.Email = email;
                entity.IsAvailable = "1";
                entity.CreateTime = DateTime.Now;
                entity.UpdateTime = DateTime.Now;
                db.User3s.Add(entity);

                User3Pwd user3pwd = new User3Pwd();
                user3pwd.Id = entity.Id;
                user3pwd.Password = TextHelper.GetMd5("123456");
                if (!string.IsNullOrEmpty(passWord)) user3pwd.Password = passWord;

                db.User3Pwds.Add(user3pwd);

                await db.SaveChangesAsync();

                Dictionary<string, string> user3 = null;
                user3 = new Dictionary<string, string>();
                foreach (PropertyInfo pi in entity.GetType().GetProperties())
                {
                    object obj = pi.GetValue(entity, null);
                    if (obj != null) user3[pi.Name] = obj.ToString();
                }
                return user3;
            }
            finally
            {
                db.Dispose();
            }
        }

        //获取user4信息
        public IDictionary<string, string> GetUser4Detail(string user4Id)
        {
            do4ADbContext db = new do4ADbContext();
            Dictionary<string, string> userDetail = null;
            try
            {
                var entity = db.User4s.Find(user4Id);
                if (entity != null)
                {
                    userDetail = new Dictionary<string, string>();
                    foreach (PropertyInfo pi in entity.GetType().GetProperties())
                    {
                        object obj = pi.GetValue(entity, null);
                        if (obj != null) userDetail[pi.Name] = obj.ToString();
                    }
                }
                return userDetail;
            }
            finally
            {
                db.Dispose();
            }
        }

        public async Task<IDictionary<string, string>> GetUser4DetailAsync(string user4Id)
        {
            do4ADbContext db = new do4ADbContext();
            Dictionary<string, string> userDetail = null;
            try
            {
                var entity = await db.User4s.FindAsync(user4Id);
                if (entity != null)
                {
                    userDetail = new Dictionary<string, string>();
                    foreach (PropertyInfo pi in entity.GetType().GetProperties())
                    {
                        object obj = pi.GetValue(entity, null);
                        if (obj != null) userDetail[pi.Name] = obj.ToString();
                    }
                }
                return userDetail;
            }
            finally
            {
                db.Dispose();
            }
        }

        public async Task<IDictionary<string, string>> PostUser4Async(string id, string code, string mobilePhone, string email, string name, string passWord)
        {
            do4ADbContext db = new do4ADbContext();
            try
            {
                if (!string.IsNullOrEmpty(id))
                {
                    var old = await db.User4s.Where(t => t.Id == id).FirstOrDefaultAsync();
                    if (old != null) throw new UserException("Id不能重复:" + id + "已存在");
                }
                if (!string.IsNullOrEmpty(code))
                {
                    var old = await db.User4s.Where(t => t.Code == code).FirstOrDefaultAsync();
                    if (old != null) throw new UserException("编码不能重复:" + code + "已存在");
                }
                if (!string.IsNullOrEmpty(mobilePhone))
                {
                    var old = await db.User4s.Where(t => t.MobilePhone == mobilePhone).FirstOrDefaultAsync();
                    if (old != null) throw new UserException("电话不能重复:" + mobilePhone + "已存在");
                }
                if (!string.IsNullOrEmpty(email))
                {
                    var old = await db.User4s.Where(t => t.Email == email).FirstOrDefaultAsync();
                    if (old != null) throw new UserException("邮箱不能重复:" + email + "已存在");
                }

                User4 entity = new User4();
                entity.Id = doServices.Instance.DoCore.getGUID();
                if (!string.IsNullOrEmpty(id)) entity.Id = id;
                entity.Name = name;
                entity.MobilePhone = mobilePhone;
                entity.Email = email;
                entity.IsAvailable = "1";
                entity.CreateTime = DateTime.Now;
                entity.UpdateTime = DateTime.Now;
                db.User4s.Add(entity);

                User4Pwd user4pwd = new User4Pwd();
                user4pwd.Id = entity.Id;
                user4pwd.Password = TextHelper.GetMd5("123456");
                if (!string.IsNullOrEmpty(passWord)) user4pwd.Password = passWord;

                db.User4Pwds.Add(user4pwd);

                await db.SaveChangesAsync();

                Dictionary<string, string> user4 = null;
                user4 = new Dictionary<string, string>();
                foreach (PropertyInfo pi in entity.GetType().GetProperties())
                {
                    object obj = pi.GetValue(entity, null);
                    if (obj != null) user4[pi.Name] = obj.ToString();
                }
                return user4;
            }
            finally
            {
                db.Dispose();
            }
        }


        //获取部门信息
        public IDictionary<string, string> GetDeptDetail(string deptId)
        {
            do4ADbContext db = new do4ADbContext();
            Dictionary<string, string> deptDetail = null;
            try
            {
                var entity = db.Depts.Find(deptId);
                if (entity != null)
                {
                    deptDetail = new Dictionary<string, string>();
                    foreach (PropertyInfo pi in entity.GetType().GetProperties())
                    {
                        object obj = pi.GetValue(entity, null);
                        if (obj != null) deptDetail[pi.Name] = obj.ToString();
                    }
                }
                return deptDetail;
            }
            finally
            {
                db.Dispose();
            }
        }

        public async Task<IDictionary<string, string>> GetDeptDetailAsync(string deptId)
        {
            do4ADbContext db = new do4ADbContext();
            Dictionary<string, string> deptDetail = null;
            try
            {
                var entity = await db.Depts.FindAsync(deptId);
                if (entity != null)
                {
                    deptDetail = new Dictionary<string, string>();
                    foreach (PropertyInfo pi in entity.GetType().GetProperties())
                    {
                        object obj = pi.GetValue(entity, null);
                        if (obj != null) deptDetail[pi.Name] = obj.ToString();
                    }
                }
                return deptDetail;
            }
            finally
            {
                db.Dispose();
            }
        }


        /// <summary>
        /// 通过部门Id获取用户列表
        /// </summary>
        /// <returns></returns>
        public async Task<List<string>> GetUser1IdsByDept(string deptId, bool isLookChildDept)
        {
            do4ADbContext db = new do4ADbContext();
            List<string> deptIds = null;
            try
            {
                if (isLookChildDept)
                {
                    var dept = await db.Depts.FirstOrDefaultAsync(t => t.Id == deptId);
                    if (dept == null) throw new UserException("当前部门不存在");
                    deptIds = await db.Depts.Where(t => t.Path.StartsWith(dept.Path))
                        .Select(t => t.Id).ToListAsync();
                }
                else
                {
                    deptIds = await db.Depts.Where(t => t.Id == deptId)
                        .Select(t => t.Id).ToListAsync();
                }
                var user1Ids = await db.User1s.Where(t => deptIds.Contains(t.DeptId))
                    .Select(t => t.Id).ToListAsync();
                return user1Ids;
            }
            finally
            {
                db.Dispose();
            }

        }


        //获取用户第三方认证信息
        public IDictionary<string, string> GetThirdPartUserDetail(string user2Id, string appType, string openId)
        {
            do4ADbContext db = new do4ADbContext();
            try
            {
                Dictionary<string, string> userDetail = null;
                ThirdPartUser entity;
                if (!string.IsNullOrEmpty(user2Id))
                {
                    entity = db.ThirdPartUser2s.Where(t => t.UserId == user2Id).FirstOrDefault();
                }
                else
                {
                    entity = db.ThirdPartUser2s.Where(t => t.AppType == appType && t.OpenId == openId).FirstOrDefault();
                }
                if (entity != null)
                {
                    userDetail = new Dictionary<string, string>();
                    foreach (PropertyInfo pi in entity.GetType().GetProperties())
                    {
                        object obj = pi.GetValue(entity, null);
                        if (obj != null) userDetail[pi.Name] = obj.ToString();
                    }
                }
                return userDetail;
            }
            finally
            {
                db.Dispose();
            }
        }

        public async Task<IDictionary<string, string>> GetThirdPartUserDetailAsync(string user2Id, string appType, string openId)
        {
            do4ADbContext db = new do4ADbContext();
            try
            {
                Dictionary<string, string> userDetail = null;
                ThirdPartUser entity;
                if (!string.IsNullOrEmpty(user2Id))
                {
                    entity = await db.ThirdPartUser2s.Where(t => t.UserId == user2Id).FirstOrDefaultAsync();
                }
                else
                {
                    entity = await db.ThirdPartUser2s.Where(t => t.AppType == appType && t.OpenId == openId).FirstOrDefaultAsync();
                }
                if (entity != null)
                {
                    userDetail = new Dictionary<string, string>();
                    foreach (PropertyInfo pi in entity.GetType().GetProperties())
                    {
                        object obj = pi.GetValue(entity, null);
                        if (obj != null) userDetail[pi.Name] = obj.ToString();
                    }
                }
                return userDetail;
            }
            finally
            {
                db.Dispose();
            }
        }


    }
}